package com.yuxi;

/**
 * Created by yuxi on 17/2/1.
 */
public class TxDemo {
    public static void main(String[] args) {
        Object object = new Object();
        String name = "yuxi";
        ThreadA threadA = new ThreadA(object,null);
        ThreadB threadB = new ThreadB(object,name);
        new Thread(threadA).start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(threadB).start();
    }

    static class ThreadA implements Runnable {
        private Object object;
        private String name;

        public ThreadA(Object object, String name) {
            this.object = object;
            this.name = name;
        }

        public void run() {
            try {
                synchronized (object) {
                    if (name == null) {
                        System.out.println( Thread.currentThread().getName() + "..." + System.currentTimeMillis());
                        object.wait();
                        System.out.println("..."+Thread.currentThread().getName()+".....wait");
                        System.out.println( Thread.currentThread().getName() + "..." + System.currentTimeMillis());
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class ThreadB implements Runnable {
        private Object object;
        private String name;

        public ThreadB(Object object, String name) {
            this.object = object;
            this.name = name;
        }

        public void run() {
            synchronized (object) {
                if (name != null) {
                    System.out.println( Thread.currentThread().getName() + "..." + System.currentTimeMillis());
                    object.notify();
                    System.out.println("..."+Thread.currentThread().getName()+".....notify");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println( Thread.currentThread().getName() + "..." + System.currentTimeMillis());
                }
            }
        }
    }
}
